package com.tangcl.module_mine.ui.activity

import android.os.Looper
import android.os.Message
import android.text.method.ScrollingMovementMethod
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.tangcl.module_base.log.LogUtils
import com.tangcl.module_base.network.RetrofitManager
import com.tangcl.module_base.utils.ToastUtils
import com.tangcl.module_commom.utils.Constants
import com.tangcl.module_commom.base.BaseActivity
import com.tangcl.module_commom.base.BaseWeakReferenceHandler
import com.tangcl.module_commom.network.BaseNetResponse
import com.tangcl.module_mine.R
import com.tangcl.module_mine.bean.UserInfo
import com.tangcl.module_mine.network.MineApiService
import com.tangcl.module_mine.network.MineLoginRepo
import com.tangcl.module_mine.network.MineProjectRepo
import com.tangcl.module_mine.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.mine_activity_user_info.*
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

//import org.koin.androidx.viewmodel.ext.android.viewModel
/**
 * Created by TCL on 2021/10/8
 *
 * description:
 */
class UserInfoActivity : BaseActivity() {
    private lateinit var myHandler: MyHandler
    private lateinit var myThread: Thread
    private var isStart: Boolean = false
    private val mainScope = MainScope()

    //    private val mViewModel: UserViewModel by viewModel()
    private val mViewModel: UserViewModel = UserViewModel(MineLoginRepo())

    override fun getLayoutId(): Int {
        return R.layout.mine_activity_user_info
    }

    override fun initData() {
        myHandler = MyHandler(Looper.getMainLooper(), this)
        myThread = object : Thread() {
            override fun run() {
                myHandler.sendEmptyMessage(0)
            }
        }
    }

    override fun initView() {
        initObserve()
        tv_info.movementMethod = ScrollingMovementMethod.getInstance()
    }

    private fun initObserve() {
//        mViewModel.loginLiveData.observe(this, object : IStateObserver<LoginResp>(null) {
//            override fun onDataChange(data: LoginResp?) {
//                showToast("登录成功")
//                SpUtils.put(SP_KEY_USER_INFO_NAME, data?.nickname)
//                //DbHelper.insertUserInfo(this, it)
//                LiveDataBus.get().with(KEY_LIVEDATA_BUS_LOGIN)
//                    .postValue(data)
//                finish()
//            }
//
//            override fun onReload(v: View?) {
//                TODO("Not yet implemented")
//            }
//        })

        mViewModel.loginLiveData.observe(this, Observer {
//            val userBean:UserInfo = it.data
//            tv_info.text = Gson().toJson(userInfo)
        })
    }

    override fun setListener() {
        btn_request.setOnClickListener {
            checkLogin(1)
        }

        btn_request_suspend.setOnClickListener {
            checkLogin(2)
        }

        btn_request_suspend_diy.setOnClickListener {
            checkLogin(3)
        }

        btn_clear.setOnClickListener {
            tv_info.text = ""
        }


        btn_handler.setOnClickListener {
            if (!isStart) {
                isStart = true
                myThread.start()
            } else {
                LogUtils.v("${getTagName()}线程", "${myThread.isAlive}")
                myHandler.currentIndex = 0
                myHandler.removeCallbacksAndMessages(null)
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        myThread.interrupt()
        myHandler.removeCallbacksAndMessages(null)
        mainScope.cancel()
    }

    /**
     * @param type 1普通  2协程suspend 3协程suspend封装
     */
    private fun checkLogin(type: Int) {
        if (cb_use_default.isChecked) {
            when (type) {
                1 -> {
                    doLogin()
                }
                2 -> {
                    doSuspendLogin()
                }
                3 -> {
                    doDiySuspendLogin()
                }
            }
        } else {
            val name = et_name.text.toString().trim()
            val psw = et_psw.text.toString().trim()

            when {
                name.isEmpty() -> {
                    ToastUtils.toastNormal(this, "请输入用户名")
                }
                psw.isEmpty() -> {
                    ToastUtils.toastNormal(this, "请输入密码")
                }
                else -> {
                    when (type) {
                        1 -> {
                            doLogin(false, name, psw)
                        }
                        2 -> {
                            doSuspendLogin(false, name, psw)
                        }
                        3 -> {
                            doDiySuspendLogin(false, name, psw)
                        }
                    }
                }
            }
        }
    }

    private fun doLogin(isUseDefault: Boolean = true, name: String = "", psw: String = "") {
        LogUtils.v("请求", "请求开始")
        val map = HashMap<String, String>()
        map["username"] = if (isUseDefault) Constants.USER_NAME else name
        map["password"] = if (isUseDefault) Constants.USER_PSW else psw
        val call =
            RetrofitManager.initRetrofit().getService(MineApiService::class.java).doLogin(map)
        call.enqueue(object : Callback<BaseNetResponse<UserInfo>> {
            override fun onFailure(call: Call<BaseNetResponse<UserInfo>>, t: Throwable) {
                LogUtils.v("请求结果", "onFailure")
            }

            override fun onResponse(
                call: Call<BaseNetResponse<UserInfo>>,
                response: Response<BaseNetResponse<UserInfo>>
            ) {
                LogUtils.v("请求结果--responseBody", "" + response.body())
                val bean: BaseNetResponse<UserInfo>? = response.body()
                if (bean?.errorCode == 0) {
                    val userInfo: UserInfo = bean.data!!
                    LogUtils.v("请求结果--bean", "" + Gson().toJson(userInfo))
                    tv_info.text = Gson().toJson(userInfo)
                } else {
                    tv_info.text = ""
                    bean?.errorMsg?.let { ToastUtils.toastNormal(this@UserInfoActivity, it) }
                }
            }

        })
    }

    private fun doSuspendLogin(
        isUseDefault: Boolean = true,
        name: String = "",
        psw: String = ""
    ) {
        val username = if (isUseDefault) Constants.USER_NAME else name
        val password = if (isUseDefault) Constants.USER_PSW else psw
        mainScope.launch {
            val user: UserInfo = MineProjectRepo().userLogin(username, password)
            tv_info.text = Gson().toJson(user)
        }
    }

    private fun doDiySuspendLogin(
        isUseDefault: Boolean = true,
        name: String = "",
        psw: String = ""
    ) {
        val username = if (isUseDefault) Constants.USER_NAME else name
        val password = if (isUseDefault) Constants.USER_PSW else psw
        mViewModel.login(username, password)
    }

    /**
     * BaseWeakReferenceHandler使用例子
     *
     */
    private class MyHandler(loop: Looper?, referencedObject: UserInfoActivity?) :
        BaseWeakReferenceHandler<UserInfoActivity?>(loop, referencedObject) {

        var currentIndex: Int = 0


        override fun handleMessage(msg: Message) {
            val activity: UserInfoActivity? = referencedObject
            activity?.let {
                when (msg.what) {
                    0 -> {
                        it.tv_info.text = "收到message:次数---$currentIndex"
                        sendEmptyMessageDelayed(0, 2000)
                    }
                    else -> {

                    }
                }
                currentIndex++
            }
        }
    }

}